<template>
  <!-- 内部调拨-新增 -->
  <div class="e-form">
      <BillTop title="物资调拨新增" @cancel="cancel"></BillTop>
    <div class="tabs">
      <div class="tabs-title">基本信息</div>
      <div style="width: 100%" class="form">
        <el-form :model="formData" label-width="150px"  :rules="rules"
          ref="formData"
          class="demo-ruleForm">
          <el-row>
            <el-col :span="12">
               <el-form-item label="调出机构：">
                 {{formData.transferOutUnitName}}
              </el-form-item>
            </el-col>
            <el-col :span="12">
                <el-form-item label="币种：" prop="currency">
                            <el-select
                                v-model="formData.currencyId"
                                placeholder="请选择"
                                @change="currencyChange"
                                v-if="!isRedSingle"
                            >
                                <el-option
                                    v-for="(
                                        item
                                    ) in currencyForm"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                >
                                </el-option>
                            </el-select>
                             <span v-else>{{formData.currency}}</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
                 <el-form-item label="调拨日期：" prop="transferDate">
                    <el-date-picker
                      v-model="formData.transferDate"
                      type="date"
                       :placeholder="geyDate()"
                       v-if="!isRedSingle"
                      value-format="yyyy-MM-dd"
                      :clearable="false"
                    >
                    </el-date-picker>
                    <span v-else>{{formData.transferDate}}</span>
                   </el-form-item>
            </el-col>
            <el-col :span="12">
                <el-form-item label="发货人员：">
                  {{formData.issuingPersonnelName}}
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
                <el-form-item label="调拨数量：">
                          {{ formData.quantity }}
                        </el-form-item>
            </el-col>
            <el-col :span="12">
               <el-form-item label="调拨金额(元)：">
                          {{ formData.amount }}
                        </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
               <el-form-item label="状态：">
              {{ '草稿' }}
            </el-form-item>
            </el-col>
            <el-col :span="12">
               <el-form-item label="本位币：">
                  {{ formData.baseCurName }}
                </el-form-item>
            </el-col>
          </el-row>
           <el-row>
              <el-col :span="12">
                <el-form-item label="本位币汇率：">
                <span v-if="formData.baseCurRate === 1">  {{ formData.baseCurRate }}</span>
                <span v-else>
                  <el-input
                    placeholder="请输入本位币汇率"
                    v-model="formData.baseCurRate"
                  >
                  </el-input>
                    </span>
                </el-form-item>

              </el-col>
              <el-col :span="12">
                  <el-form-item label="人民币汇率：">
                <span>{{ formData.rmbRate }}</span>
                </el-form-item>
                 </el-col>
            </el-row>
          <el-row>
            <el-form-item label="备注：">
              <el-input
                type="textarea"
                :rows="2"
                placeholder="请输入内容"
                v-model="formData.remarks"
              >
              </el-input>
            </el-form-item>
          </el-row>
           <el-row>
              <el-form-item label="冲红单" v-if="isRedSingle"
                  ><span :style="redBillStateStyle">{{
                      redBillStateFun
                  }}</span></el-form-item
              >
            </el-row>
        </el-form>
      </div>
    </div>
    <div class="buttons">
       <span class="tip"
        ><span style="color: red; margin-right: 0">*</span>为必填项</span
      >
      <el-button type="primary" style="background: #2e61d7" @click="save('formData')"
        >保存</el-button
      >
      <el-button @click="cancel()">关闭</el-button>
    </div>
  </div>
</template>

<script>
import '@/utils/jquery.scrollTo.min'
import {  mapState } from 'vuex'
import { getRmbRate } from '@/api/equip/common.js'
import {
    showLoading,
    hideLoading,
} from '@/utils/common'
import Api from '@/api/materials/interiorAllot.js'

export default {
    data () {
        return {
            //表单数据
            formData: {
                'amount': 0,
                'baseCurAmount': 0,
                'baseCurId': '',
                'baseCurName': '',
                'baseCurRate': 0,
                'billId': '',
                'billNo': '',
                'businessType': 0,
                'contractId': '',
                'contractName': '',
                'currency': '',
                'currencyId': '',
                'dataSources': 0,
                'founderId': '',
                'founderName': '',
                'gmtCreate': '',
                'gmtModified': '',
                'isRed': 0,
                'issuingPersonnelId': '',
                'issuingPersonnelName': '',
                'nullifyCreated': '',
                'nullifyCreator': '',
                'nullifyCreatorId': '',
                'nullifyDescription': '',
                'nullifyReason': '',
                'orgId': '',
                'orgName': '',
                'pickingPersonnelId': '',
                'pickingPersonnelName': '',
                'quantity': 0,
                'redBillId': '',
                'redBillNo': '',
                'redBillState': '',
                'remarks': '',
                'rmbAmount': 0,
                'rmbId': '',
                'rmbName': '',
                'rmbRate': 0,
                'sourceId': '',
                'sourceNumber': '',
                'state': '',
                'transferDate': '',
                'transferInUnitId': '',
                'transferInUnitName': '',
                'transferOutUnitId': '',
                'transferOutUnitName': '',
                'workId': '',

            },
            orgId: '', //机构id
            orgName: '', //机构名称
            isSkip: false, //是否跳转
            //验证
            rules: {
                transferDate: [
                    {  required: true, message: '请选择调拨日期', trigger: 'change' }
                ],
                currency: [
                    {  required: true, message: '请至少选择一个币种', trigger: 'change' }
                ],
            },
            isRedSingle: false,
            redFormData: null,
            redBillStateStyle: {
                width: '300px',
                height: '30px',
                color: '#fff',
                backgroundColor: '',
                'text-align': 'center'
            },
        }
    },
    watch: {
        'formData.redBillState' () {
            if (this.formData.redBillState == '3') {
                this.redBillStateStyle.backgroundColor = '#FF2300'
            } else if (
                this.formData.redBillState == '0' ||
                this.formData.redBillState == '1'
            ) {
                this.redBillStateStyle.backgroundColor = '#FFA40D'
            } else if (this.formData.redBillState == '2') {
                this.redBillStateStyle.backgroundColor = 'rgb(153,153,153)'
            }
        }
    },
    computed: {
        ...mapState({
            userInfo: state => state.userInfo,
            currencyForm: state => state.equip.equipData.currencyForm, //币种
            options: state => state.contract.ctClassify,
        }),
        //状态
        statusLable () {
            return param => {
                const state = this.$store.state.equip.equipData.state
                const obj = state.find(x => x.value == param)
                return obj ? obj.label : ''
            }
        },
        // 红单状态
        redBillStateFun () {
            let redState = ''
            switch (this.formData.redBillState) {
            case '0':
                redState = '冲销中'
                break
            case '1':
                redState = '冲销中'
                break
            case '2':
                redState = '已冲销'
                break
            case '3':
                redState = '红单'
                break
            }
            return redState
        }

    },
    components: {},
    created () {
        try {
            let data = JSON.parse(localStorage.getItem('vuex'))
            this.orgId = data.userInfo.orgInfo.orgId
            this.formData.transferOutUnitName = data.userInfo.orgInfo.orgName
            this.formData.issuingPersonnelName = localStorage.getItem('userName')
            this.formData.issuingPersonnelId = localStorage.getItem('userId')
            this.getinfo()
            this.geyDate()
            this.$route.query.isRedSingle === '1' || this.$route.query.isRedSingle === '2'
                ? (this.isRedSingle = true)
                : (this.isRedSingle = false)
            if (this.$route.query.isRedSingle === '1') {
                this.getRedList()
            }else if(this.$route.query.isRedSingle === '2') {
                this.estimatedAcceptanceRedSingle()
            }
        } catch (error) {
            alert(error.message)
        }
    },
    mounted () {},
    beforeDestroy () {},
    methods: {
        getinfo () {
            try {
                const { baseCyByOrgId } = this.userInfo
                this.formData.baseCurName = baseCyByOrgId.currencyName  //本位币
                this.formData.baseCurId = baseCyByOrgId.currency
            } catch (error) {
                alert(error.message)
            }

        },
        // 如果是点击冲红单进入的新增页,则需要返显数据,只有备注能修改,其余均不能修改
        async getRedList () {
            showLoading()
            try {
                let data = await Api.redSingle(this.$route.query.billid)
                this.redFormData = this._.cloneDeep(data)
                // data.businessType = this.businessTypeList.find(
                //     item => item.value === data.businessType
                // ).key
                // data.currency = this.currencyForm.find(
                //     x => x.value === data.currencyId
                // ).label
                this.formData = data
            } finally {
                hideLoading()
            }
        },

        //币种切换
        currencyChange (val) {
            this.formData.currency = this.currencyForm.find(x=>x.value === val).label  //币种

            getRmbRate({  //获取机构下某币种的人民币汇率
                currency: val,
                orgId: this.userInfo.orgInfo.orgId
            }).then(res=>{
                console.log('res', res)
                // this.formData.rmbId = res.rateId
                // this.formData.rmbName = res.rate
                // this.formData.rmbRate = res.rate
                if(res.rate === 1) {
                    this.formData.rmbRate = res.rate
                    this.formData.rmbId = res.currency
                }else{
                    this.formData.rmbRate = res.rate
                    this.formData.rmbId = res.rateId
                }

            }).catch(()=>{

            })

            if(this.formData.currencyId === this.formData.baseCurId) {   //币种=本位币
                this.formData.baseCurRate = 1
                this.showBaseCurName = false
            }else{
                this.formData.baseCurRate = null
                this.showBaseCurName = true
            }
        },
        //保存
        save (formName) {
            if(this.formData.transferDate === '') {
                this.formData.transferDate = this.geyDate()
            }
            this.$refs[formName].validate(valid => {
                if (valid) {
                    if (this.isRedSingle) {
                        this.redFormData.remarks = this.formData.remarks
                    }
                    Api.AddInteriorAllot(this.isRedSingle ? this.redFormData : this.formData).then(res => {
                        this.clientPop('suc', '保存成功,是否继续', ()=>{
                            this.$router.replace({
                                path: '/interiorAllotEdit',
                                query: {
                                    billid: res,
                                    name: 'receivingMaterials'
                                }
                            })
                        }, this.cancel)

                    })
                } else {
                    return false
                }
            })

        },
        //取消按钮
        cancel () {
            this.$router.replace('/interiorAllot')
        },
        //获取当前时间
        geyDate () {
            var myDate = new Date()
            let y = myDate.getFullYear()
            let m = myDate.getMonth() + 1
            let d = myDate.getDate()
            m = m < 10 ? '0' + m : m //小于10补0
            d = d < 10 ? '0' + d : d //小于10补0
            console.log('date', `${y}-${m}-${d}` )
            return `${y}-${m}-${d}`
        },
    },
}
</script>

<style lang="scss" scoped>
.buttons {
  left: 0;
}
.e-form {
  margin-bottom: 80px;
  padding: 0 20px;
  .tabs-title::before {
    content: "";
    height: 22px;
    width: 8px;
    border-radius: 40px;
    background-color: #2e61d7;
    display: block;
    position: absolute;
    left: 20px;
    margin-right: 20px;
  }
}

.e-table {
  background: #fff;
}

.el-tab-pane {
  margin-left: -10px;
}
</style>
